import React from 'react';
import {toJS} from 'mobx';
import { inject, observer } from 'mobx-react';
import { WeaDialog, WeaNewScroll, WeaSelect, WeaBrowser, WeaDatePicker, WeaTimePicker, WeaTextarea, WeaInput, WeaUpload ,WeaInputNumber,WeaSearchGroup,WeaFormItem} from 'ecCom';
import { Button, Spin, Row, Col, Input, Radio, Checkbox, Modal, DatePicker } from 'antd';
import {WeaSwitch} from 'comsMobx';
import Collapse from './collapse.js'
import isEmpty from 'lodash/isEmpty';
import MySwitch from './mySwitch';
import {WeaLocaleProvider,WeaTools,WeaCheckbox} from 'ecCom';
const getKey = WeaTools.getKey;
const getLabel = WeaLocaleProvider.getLabel;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;

@inject('createWorkPlanStore')
@inject('myWorkPlanStore')
@observer
class Create extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectTypeOption:[],
    }
  }
  componentDidMount() {
    eventRegister.loadModule && eventRegister.loadModule('b_workplan', ()=> {
      // 加载成功
      
    }, ()=> {
        // console.log("加载失败");
        // 加载文件失败 的业务处理， 网络超时，没文件之类
    })
  }

  componentWillReceiveProps(nextProps) {
    let {msg, setParam}=this.props.createWorkPlanStore;
    setTimeout(function(){setParam({msg:''})},3*1000)
  }

  componentWillUnmount() {
    //组件卸载时一般清理一些状态

  }

  getFields = () => {
    let {  isEdit } = this.props;
    let { form, status, workPlanId, setSelectTypeOption,msg,uploadParams ,setUploadParams} = this.props.createWorkPlanStore;
    uploadParams = toJS(uploadParams);
    let {refreshSelectType}=this.props.myWorkPlanStore;
    const {isFormInit} = form;
    let group = [];
    const {fields, workplanTypeOptions} = toJS(status);
    const formParams = form.getFormParams();
    isFormInit && fields && fields.map((c, _index) =>{
      let items = [];
      c.items.map(fields => {

        if(fields.domkey[0] == 'planName' && formParams && formParams[fields.domkey[0]] ) {
          let val = formParams[fields.domkey[0]] || '';
          val = val.replace(/&lt;br&gt;/g,' ');
          val = val.replace(/&lt;\/br&gt;/g,' ');
          val = val.replace(/(<br>|<\/br>)/g,' ');
          val = val.replace(/>/g,' ');

          form.updateFields({
            [fields.domkey[0]]: val
          })
        }

        if (fields.conditionType == 'BROWSER') {
          fields = this.browserDemand(fields, formParams)
        }

        if((!formParams['remindType']) &&
          (fields.domkey[0] == 'remindImmediately' || 
            fields.domkey[0] == 'remindBeforeStart' ||
            fields.domkey[0] == 'remindBeforeEnd')) {
          return
        } else if(fields.domkey[0] == 'workPlanType') {
          fields.options = workplanTypeOptions
          items.push({
            com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@1krcfk@${fields.domkey[0]}`}
              label={`${fields.label}`}
              labelCol={{span: `${fields.labelcol}`}}
              wrapperCol={{span: `${fields.fieldcol}`}}
              error={form.getError(fields)}
              >
              <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@86v5ng@${fields.domkey[0]}`}
                  {...fields}
                  onChange={(v)=>this.updateWPType(v)}
                  addOnClick={() => {
                    let url = '/spa/workplan/static4engine/engine.html#/workplanengine/typeSet?isRoute=true&isEdit='+isEdit+'&workplanId='+workPlanId;
                    const dialog = WeaTools.createDialog({
                        title: getLabel(19773, '日程类型设置'),
                        moduleName: "schedule",
                        url: url,
                        draggable: false,
                        style: {width:800,height:600},
                        callback: (datas) =>{
                            if(datas){
                              setSelectTypeOption(datas);
                              refreshSelectType();
                            }
                        },
                        onCancel: () =>{
                        }
                    });
                    dialog.show();
                  }}
                />
            </WeaFormItem>),
            colSpan: 1
          })
        } else {
          if(fields.domkey[0] == 'remindBeforeStart' || fields.domkey[0] == 'remindBeforeEnd'){//提醒开始时间 提醒结束时间 上传组件单独处理
            items.push({
              com: (<WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@gdac8c@${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{span: `${fields.labelcol}`}}
                wrapperCol={{span: `${fields.fieldcol}`}}
                >
                <MySwitch ecId={`${this && this.props && this.props.ecId || ''}_MySwitch@7u0wxt@${fields.domkey[0]}`} fieldConfig={fields} form={form} onChange={this.onChange}/>
              </WeaFormItem>),
              colSpan: 1
            })
          }else {
            items.push({
              com:(
                <WeaFormItem ecId={`${this && this.props && this.props.ecId || ''}_WeaFormItem@6av6pb@${fields.domkey[0]}`}
                  label={`${fields.label}`}
                  labelCol={{span: `${fields.labelcol}`}}
                  wrapperCol={{span: `${fields.fieldcol}`}}
                  tipPosition="top"
                  error={form.getError(fields)}
                >
                  {fields.conditionType == 'UPLOAD' ?
                  <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@05ymxo@${fields.domkey[0]}`}
                    {...uploadParams[fields.domkey]}
                    onChange={(ids, list) => {
                      form.updateFields({
                        [fields.domkey]: ids
                      })
                      setUploadParams({
                        [fields.domkey]: {
                          datas: list
                        }
                      })
                    }}
                  />
                   :<WeaSwitch ecId={`${this && this.props && this.props.ecId || ''}_WeaSwitch@8692c1@${fields.domkey[0]}`} fieldConfig={fields} form={form} formParams={formParams} onChange={this.onChange}/>
                }
                  {fields.domkey[0] == 'memberIDs'&&msg.length>0?<span className={'resource-warn'} style={{display:msg==''||msg==undefined?'none':''}}>{msg}</span>:''}
                </WeaFormItem>),
              colSpan:1,
            })
          }
        }
      });
      group.push(<WeaSearchGroup ecId={`${this && this.props && this.props.ecId || ''}_WeaSearchGroup@irluav@${_index}`} col={1} needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    return group;
  }

  browserDemand = (oldFields, oldValue)=>{
    let newFields = {...oldFields}
    let newValue = {...oldValue}
    newFields.browserConditionParam.dataParams = {...newFields.browserConditionParam.dataParams,secretLevel: newValue['secretLevel'] ? newValue['secretLevel'] : ''}
    newFields.browserConditionParam.completeParams = {...newFields.browserConditionParam.completeParams,secretLevel: newValue['secretLevel'] ? newValue['secretLevel'] : ''}
    return newFields
  }
  
  render() {
    // const {loading} = this.props
    let title = `${getLabel(18481,'新建日程')}`;
    let { visible,  isEdit, workPlanTypeOptions} = this.props;
    let {selectTypeOption,setSelectTypeOption,workPlanId,scrollHeight,sqlWhere,msg,isOpenSecret,
      isPro}=this.props.createWorkPlanStore;
    let {refreshSelectType}=this.props.myWorkPlanStore;
    // if (workPlanTypeOptions) {
    //   if (workPlanTypeOptions == 3) {
    //     options = [{ 'key': '3', 'showname': getLabel(6082,'客户联系') }]//下拉框数据,客户模块的新建

    //   }else if(workPlanTypeOptions == 2){
    //     options = [{ 'key': '2', 'showname': getLabel(16095,'项目日程') }]//下拉框数据,客户模块的新建
    //   }
    // }
    return (
      <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@g59900`} height={this.props.isSingle ? '100%' : scrollHeight || '500px'}>
        <div className="workPlan-createWorkPlan" id="workPlan-createWorkPlan-id">
          {this.getFields()}
        </div>
      </WeaNewScroll>
    )
  }

  updateWPType = (value)=>{
    let {form} = this.props.createWorkPlanStore;
    form.updateFields({
      workPlanType: {
        value: value
      }
    })
  }

  onChange = (paramsObj) => {
    let {form, setState , setOldSecretLevel,oldSecretLevel} = this.props.createWorkPlanStore;
    let params={};
    if (paramsObj.secretLevel) {//判断密级
      //密级等级是否小于当前使用等级
      const secretLevel = paramsObj['secretLevel'].value
      if(parseInt(secretLevel,10) > parseInt(oldSecretLevel,10)){
        let _that = this
        //清空文档和流程
        Modal.confirm({
          title: `${getLabel(131329,'信息确认')}`,
          content: `${getLabel(500701,'【密级】级别已更改且小于上次选择，文档、流程资源会被清空')}`,
          onOk() {
            //更新会议信息中的字段
            form.updateFields({
              docIDs: {
                value: '',
                valueSpan: '',
                valueObj: ''
              },
              requestIDs: {
                value: '',
                valueSpan: '',
                valueObj: ''
              },
              secretLevel:secretLevel
            })

            setOldSecretLevel(paramsObj['secretLevel'].value)
          },
          onCancel() {
            form.updateFields({
              secretLevel: {
                value: oldSecretLevel
              }
            })
          },
        });
      }else{
        setOldSecretLevel(paramsObj['secretLevel'].value)
      }
      
    }
  }

}

export default Create
